package com.definity.toolkit.storage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.definity.toolkit.persistence.Repository;
import com.definity.toolkit.persistence.RepositoryFactory;
import com.definity.toolkit.service.ServiceException;

public abstract class StorageServiceImpl<T extends StorageData, C> implements StorageService<T, C> {

	@Autowired
	private RepositoryFactory repositoryFactory;

	private final Class<T> type;

	private Repository<T> repository;
	
	public StorageServiceImpl(Class<T> type) {
		this.type = type;
	}
	
	@Override
	public T get(Long fileId) {
		return repository().findById(fileId);
	}

	@Override
	public C getContent(Long fileId) {
		return getContent(get(fileId));
	}

	public T view(T domain) {
		if (domain == null || domain.getId() == null)
			return null;
		
		return repository().findById(domain.getId());
	}
	
	@Transactional
	public void delete(T domain) {
		T d = view(domain);
		if (d == null)
			throw new ServiceException("delete.domain.null");
		
		repository().delete(d);
	}
	
	@Transactional
	protected T save(T data) {
		if (data.getGroup() == null)
			data.setGroup("_default");
		if (data.getLastModified() == null)
			data.setLastModified(System.currentTimeMillis());
		return repository().save(data);
	}
	
	protected final Repository<T> repository() {
		if (repository == null)
			repository = createRepository(repositoryFactory);
		return repository;
	}
	
	protected Repository<T> createRepository(RepositoryFactory repositoryFactory) {
		return repositoryFactory.create(type);
	}
	
}
